<template>
  <div class="app-container">
    <el-container>
      <el-header
        style="padding-top: 15px;padding-left: 850px; box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >添加药品
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-s-unfold"
              size="mini"
              :disabled="multiple"
              @click="batchSetting"
              v-hasPermi="['system:recipt:update']"
            >批量设置
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-recipt"
              size="mini"
              @click="addRecipt1"
              v-hasPermi="['system:recipt:delete']"
            >暂存
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-finished"
              size="mini"
              @click="addRecipt2"
              v-hasPermi="['system:recipt:delete']"
            >提交审核
            </el-button>
          </el-col>
        </el-row>
      </el-header>
      <el-main style="margin: 10px 0;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">
        <el-form :model="queryForm1" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="单据号" prop="reciptNum1">
            <el-input
              v-model="this.reciptNum1"
              readonly
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="制单人" prop="lister1" >
            <el-input
              v-model="this.lister1"
              readOnly
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item class="demonstration block" label="制单时间" prop="createTime" >
            <el-date-picker
              v-model="value1"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="供应商" prop="buySupplier">
            <el-select v-model="queryForm1.buySupplier" placeholder="供应商" clearable>
              <el-option
                v-for="buySupplier in buySupplierList"
                :key="buySupplier.sId"
                :label="buySupplier.sName"
                :value="buySupplier.sId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="总批发额" prop="rpTotals1" >
            <el-input
              v-model="rpTotals1"
              readonly
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-form>
      </el-main>
      <el-main style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);padding: 10px">
        <el-table border v-loading="loading" :data="reciptPhysics" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="药品ID" align="center" prop="rpPId" width="100"/>
          <el-table-column
            label="药品名称"
            align="center"
            prop="pName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="规格"
            align="center"
            prop="pNorms"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="生产厂家"
            align="center"
            prop="pFactoryName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="数量"
            align="center"
            prop="rpCount"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="单位"
            align="center"
            prop="pUnit"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="批发价"
            align="center"
            prop="rpPrice"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="批发额"
            align="center"
            prop="rpTotal"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="批发号"
            align="center"
            prop="rpNum"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="备注"
            align="center"
            prop="remark"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="操作" align="center" class-name="small-padding">
            <template slot-scope="scope">
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:reg:update']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>

    <!-- 批量设置对话框 -->
    <el-dialog :title="title" :visible.sync="show" width="500px" append-to-body style="text-align: center">
      <el-form ref="settingForm" :model="settingData" :rules="rules" label-width="80px">
        <el-form-item label="数量" prop="rpCount">
          <el-input-number v-model="settingData.rpCount" placeholder="0"/>
        </el-form-item>
        <el-form-item label="批发价格" prop="rpPrice">
          <el-input-number v-model="settingData.rpPrice" :precision='2'/>
        </el-form-item>
        <el-form-item label="批次号" prop="rpNum">
          <el-input
            v-model="settingData.rpNum"
            placeholder="请输入批次号"
            clearable :style="{width: '100%'}"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="settingData.remark"
            placeholder="请输入备注"
            clearable :style="{width: '100%'}"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="settingPhysic">确定</el-button>
        <el-button @click="DontShow">取消</el-button>
      </div>
    </el-dialog>

    <!-- 添加药品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body style="text-align: center">
      <el-form ref="form" :model="queryParams" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="关键字" prop="pKeyword">
              <el-input v-model="queryParams.pKeyword" placeholder="请输入关键字" @input="handleQuery2" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="药品类型" prop="pType">
              <el-select v-model="queryParams.pType" placeholder="药品类型" @blur="handleQuery">
                <el-option
                  v-for="dict in dict.type.drug_physic_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  @click.native="handleQuery2(dict.label)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="处方类型" prop="pRecipetype">
              <el-select v-model="queryParams.pRecipetype" placeholder="处方类型" @blur="handleQuery">
                <el-option
                  v-for="dict in dict.type.drug_physic_recipetype"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  @click.native="handleQuery2(dict.label)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table border v-loading="loading" :data="physicsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="药品ID" align="center" prop="pId" width="100"/>
        <el-table-column
          label="药品名称"
          align="center"
          prop="pName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="药品编码"
          align="center"
          prop="pCode"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="生产厂家"
          align="center"
          prop="pFactoryName"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="药品类型" align="center" prop="pType" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.drug_physic_type" :value="scope.row.pType"/>
          </template>
        </el-table-column>
        <el-table-column label="处方类型" align="center" prop="pRecipeType" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.drug_physic_recipetype" :value="scope.row.pRecipeType"/>
          </template>
        </el-table-column>
        <el-table-column
          label="关键字"
          align="center"
          prop="pKeyword"
          :show-overflow-tooltip="true"
        />
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getStoreList"
      />
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="submitForm">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import {listSupplier, getUserName, listStore,addReciptPhysic,listPhysic,addRecipt1,addRecipt2,updateSetting,delPhysicById,selectReciptByNum} from "@/api/drug/recipt";


    export default {
        name: "Notice",
        dicts: ['drug_sup_type', 'drug_physic_type','drug_physic_recipetype'],
        data() {
            return {
                value1:'',
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                //制表人
                lister1: '',
                //生成单据号
                reciptNum1: '',
                // 公告表格数据
                buySupplierList: [],
                //单据列表
                buyReciptList: [],
                //厂家药品列表
                physicsList: [],
                //单据中的药品列表
                reciptPhysics: [],
                //当前单据状态
                reciptStatus:'',
                //批发总额
                rpTotals1: 0.0,
                //数量
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                show: false,
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    pKeyword: undefined,
                    pType: undefined,
                    pRecipetype: undefined,
                },
                // 表单参数
                form: {},
                settingData:{},
                queryParams3:{
                    pageNum: 1,
                    pageSize: 10,
                    reciptNum:undefined
                },
                queryForm1: {
                    reciptNum: undefined,
                    lister: undefined,
                    createTime:undefined,
                    buySupplier:undefined,
                    rpTotals:undefined
                },
                // 表单校验
                rules: {}
            };
        },
        created() {
            this.reciptNum1 = this.$route.params.reciptNum;
            this.getSupplierList();
            this.getPhysicsList();
            this.getLister();
            if (this.reciptNum1==''|| this.reciptNum1==undefined ||this.reciptNum1==null){
                this.createRecipt();
            }
        },
        methods: {
            //获取当前订单状态
            selectReciptByNum(){
                this.queryForm1.reciptNum = this.reciptNum1
                selectReciptByNum(this.queryForm1).then(response =>{
                    this.reciptStatus=response.data.status
                    console.log(this.reciptStatus)
                })
            },
            //计算总额
            totalSum(){
                this.rpTotals1=0;
                for (let i=0;i<this.reciptPhysics.length;i++){
                    this.rpTotals1 += this.reciptPhysics[i].rpTotal
                }
            },
            //批量设置确定按钮
            settingPhysic(){
                updateSetting(this.ids,this.settingData).then(response => {
                    this.$modal.msgSuccess("设置成功");
                    this.show = false;
                    this.getPhysicsList();
                });
            },
            //暂存按钮
            addRecipt1(){
                if (this.reciptStatus==4||this.reciptStatus==1 ||this.reciptStatus==2){
                    this.$modal.msgError("单据正在审核或已通过，无法修改");
                }else {
                    this.queryForm1.reciptNum = this.reciptNum1
                    this.queryForm1.lister = this.lister1
                    this.queryForm1.createTime = this.value1
                    this.queryForm1.rpTotals = this.rpTotals1
                    addRecipt1(this.queryForm1).then(response => {
                        this.$modal.msgSuccess(response.msg);
                    })
                }
            },
            //提交审核
            addRecipt2(){
                if (this.reciptStatus==4||this.reciptStatus==1 ||this.reciptStatus==2){
                    this.$modal.msgError("单据正在审核或已通过，无法修改");
                }else {
                    this.queryForm1.reciptNum = this.reciptNum1
                    this.queryForm1.lister = this.lister1
                    this.queryForm1.createTime = this.value1
                    this.queryForm1.rpTotals = this.rpTotals1
                    addRecipt2(this.queryForm1).then(response =>{
                        this.$modal.msgSuccess(response.msg);
                    })
                }
            },
            //批量设置
            batchSetting(){
                if (this.reciptStatus==4||this.reciptStatus==1 ||this.reciptStatus==2){
                    this.$modal.msgError("单据正在审核或已通过，无法修改");
                }else {
                    this.resetForm("settingForm");
                    this.show = true;
                    this.title = "批量设置";
                }
            },
            //批量设置取消
            DontShow(){
                this.show=false;
                this.resetForm("settingForm");
            },
            /** 新增药品点击事件 */
            handleAdd() {
                if (this.reciptStatus==4||this.reciptStatus==1 ||this.reciptStatus==2){
                    this.$modal.msgError("单据正在审核或已通过，无法修改");
                }else {
                    this.reset();
                    this.open = true;
                    this.getStoreList();
                    this.title = "添加药品";
                }
            },
            /** 查询厂家药品列表 */
            getStoreList() {
                this.loading = true;
                listStore(this.queryParams).then(response => {
                    this.physicsList = response.rows;
                    this.total = response.total;
                    this.loading = false;
                });
            },
            /** 查询单据药品列表 */
            getPhysicsList() {
                this.loading = true;
                this.queryParams3.reciptNum=this.reciptNum1
                listPhysic(this.queryParams3).then(response => {
                    this.reciptPhysics = response.rows;
                    this.totalSum();
                    this.selectReciptByNum();
                    this.total = response.total;
                    this.loading = false;
                });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.form = {
                    pKeyword: undefined,
                    pType: undefined,
                    pRecipetype: undefined,
                    pId: undefined,
                    reciptNum:undefined
                };
                this.resetForm("form");
            },
            //获取登录用户姓名
            getLister() {
                this.loading = true;
                getUserName().then(response => {
                    this.lister1 = response.msg;
                    this.loading = false;
                })
            },
            //生成单据Id
            createRecipt() {
                this.reciptNum1='';
                this.reciptNum1 += 'CG';
                for (let i = 0; i < 20; i++) {
                    this.reciptNum1 += Math.floor(Math.random() * 10);
                }
            },
            //查询供应商列表
            getSupplierList() {
                this.loading = true;
                listSupplier().then(response => {
                    this.buySupplierList = response.data;
                    this.loading = false;
                });
            },
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            handleQuery2() {
                this.queryParams.pageNum = 1;
                this.getStoreList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.pId)
                this.single = selection.length != 1
                this.multiple = !selection.length
            },
            /** 关闭按钮按钮 */
            submitForm: function () {
                if (this.ids.length!=0){
                    let reAdd = true;
                    const physics=this.reciptPhysics;
                    const pIds = this.ids;
                    for(let i=0; i<physics.length;i++){
                        for(let j=0;j<pIds.length;j++){
                            if (pIds[j]==physics[i].pId){
                                reAdd=false;
                            }
                        }
                    }
                    if (reAdd){
                        addReciptPhysic(this.ids,this.reciptNum1).then(response => {
                            this.$modal.msgSuccess("添加成功");
                            this.open = false;
                            this.getPhysicsList();
                        });
                    }else{
                        this.$modal.msgWarning("部分药品已经在单据中");
                        this.open = false;
                        this.getPhysicsList();
                    }
                }
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                const physicId = row.pId || this.ids
                this.$modal.confirm('是否确认删除编号为"' + physicId + '"的药品？').then(function () {
                    return delPhysicById(physicId);
                }).then(() => {
                    this.getPhysicsList();
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => {
                });
            }
        }
    };
</script>
